import React, { useEffect, useState } from "react";
import { Table, Tag, Space, message, Popconfirm, Modal, Button,Typography } from "antd";

import service from "@/http/request";

function UserAdmin() {
  const [users, setUsers] = useState([]);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });
  const [loading, setLoading] = useState(false);

  // 控制编辑弹窗
  const [isModalVisible, setIsModalVisible] = useState(false);
  // 当前操作的用户
  const [currentUser, setCurrentUser] = useState(null);
  // 操作loading状态
  const [actionLoading, setActionLoading] = useState(false);

  // 获取用户列表
  const fetchUsers = async (page = 1, size = 10) => {
    setLoading(true);
    try {
      const res = await service.get(
        `/admin/users?pageNum=${page}&pageSize=${size}`
      );
      const { records, total } = res;
      setUsers(records);
      setPagination({
        current: page,
        pageSize: size,
        total,
      });
    } catch (error) {
      message.error("获取用户列表失败");
    }
    setLoading(false);
  };

  // 封禁用户
  const handleBanUser = async (userId) => {
    try {
      await service.put(`/admin/users/ban/${userId}`);
      message.success("用户已成功封禁");
      fetchUsers(pagination.current, pagination.pageSize);
    } catch (error) {
      message.error("封禁失败，请重试");
    }
  };

  // 解封用户
  const handleUnbanUser = async (userId) => {
    try {
      await service.put(`/admin/users/unban/${userId}`);
      message.success("用户已成功解封");
      fetchUsers(pagination.current, pagination.pageSize);
    } catch (error) {
      message.error("解封失败，请重试");
    }
  };

  // 提拔为管理员
  const handlePromote = async () => {
    if (!currentUser) return;
    setActionLoading(true);
    try {
      await service.put(`/admin/users/promote/${currentUser.id}`);
      message.success("用户已成功提拔为管理员");
      fetchUsers(pagination.current, pagination.pageSize);
      setIsModalVisible(false);
    } catch (error) {
      message.error("提拔失败，请重试");
    }
    setActionLoading(false);
  };

  // 降级为普通用户
  const handleDemote = async () => {
    if (!currentUser) return;
    setActionLoading(true);
    try {
      await service.put(`/admin/users/demote/${currentUser.id}`);
      message.success("用户已成功降级为普通用户");
      fetchUsers(pagination.current, pagination.pageSize);
      setIsModalVisible(false);
    } catch (error) {
      message.error("降级失败，请重试");
    }
    setActionLoading(false);
  };

  // 警告用户
  const handleWarn = async () => {
    if (!currentUser) return;
    setActionLoading(true);
    try {
      await service.put(`/admin/users/warn/${currentUser.id}`);
      message.success("用户已被警告");
      fetchUsers(pagination.current, pagination.pageSize);
      setIsModalVisible(false);
    } catch (error) {
      message.error("警告失败，请重试");
    }
    setActionLoading(false);
  };

  // 解除警告
  const handleUnwarn = async () => {
    if (!currentUser) return;
    setActionLoading(true);
    try {
      await service.put(`/admin/users/unwarn/${currentUser.id}`);
      message.success("用户警告已解除");
      fetchUsers(pagination.current, pagination.pageSize);
      setIsModalVisible(false);
    } catch (error) {
      message.error("解除警告失败，请重试");
    }
    setActionLoading(false);
  };

  // 打开编辑弹窗
  const showModal = (user) => {
    setCurrentUser(user);
    setIsModalVisible(true);
  };

  // 关闭弹窗
  const handleCancel = () => {
    setIsModalVisible(false);
    setCurrentUser(null);
  };

  useEffect(() => {
    fetchUsers();
  }, []);

  const columns = [
    {
      title: "用户名",
      dataIndex: "username",
      key: "username",
    },
    {
      title: "邮箱",
      dataIndex: "email",
      key: "email",
    },
    {
      title: "角色",
      dataIndex: "role",
      key: "role",
      render: (role) => {
        let color = role === "ADMIN" ? "red" : "blue";
        return <Tag color={color}>{role === "ADMIN" ? "管理员" : "用户"}</Tag>;
      },
    },
    {
      title: "等级",
      dataIndex: "level",
      key: "level",
    },
    {
      title: "积分",
      dataIndex: "credit",
      key: "credit",
    },
    {
      title: "上传次数",
      dataIndex: "uploadCount",
      key: "uploadCount",
    },
    {
      title: "下载次数",
      dataIndex: "downloadCount",
      key: "downloadCount",
    },
    {
      title: "状态",
      dataIndex: "status",
      key: "status",
      render: (status) => {
        const color = status === "ACTIVE" ? "green" : "volcano";
        return <Tag color={color}>{status === "ACTIVE" ? "活跃" : "封禁"}</Tag>;
      },
    },
    {
      title: "注册时间",
      dataIndex: "createdAt",
      key: "createdAt",
      render: (time) => new Date(time).toLocaleString(),
    },
    {
      title: "操作",
      key: "action",
      render: (_, record) => (
        <Space size="middle">
          <a onClick={() => showModal(record)}>编辑</a>
          {record.status === "ACTIVE" ? (
            <Popconfirm
              title="确定要封禁该用户吗？"
              onConfirm={() => handleBanUser(record.id)}
              okText="确定"
              cancelText="取消"
            >
              <a style={{ color: "red" }}>封禁</a>
            </Popconfirm>
          ) : (
            <Popconfirm
              title="确定要解封该用户吗？"
              onConfirm={() => handleUnbanUser(record.id)}
              okText="确定"
              cancelText="取消"
            >
              <a style={{ color: "green" }}>解封</a>
            </Popconfirm>
          )}
        </Space>
      ),
    },
  ];

  return (
    <div>
      <Table
        rowKey="id"
        loading={loading}
        columns={columns}
        dataSource={users}
        pagination={{
          ...pagination,
          showSizeChanger: true,
          onChange: (page, pageSize) => fetchUsers(page, pageSize),
        }}
      />

      {/* 编辑用户弹窗 */}
      <Modal
        title={currentUser ? `编辑用户：${currentUser.username}` : "编辑用户"}
        visible={isModalVisible}
        onCancel={handleCancel}
        footer={null} // 我们自定义底部按钮，放在内容内，避免默认挤一起
      >
        <Typography.Paragraph>
          请选择对应操作对用户进行管理。提拔或降级会更改用户角色，警告操作用于提醒用户注意社区规则。
        </Typography.Paragraph>

        <Space direction="vertical" style={{ width: "100%" }} size="large">
          <Space size="middle">
            <Button
              type="primary"
              loading={actionLoading}
              onClick={handlePromote}
            >
              提拔为管理员
            </Button>
            <Button danger loading={actionLoading} onClick={handleDemote}>
              降级为普通用户
            </Button>
          </Space>

          <Space size="middle">
            <Button
              type="default"
              loading={actionLoading}
              onClick={handleWarn}
              style={{ color: "#faad14", borderColor: "#faad14" }} // 警告色，橙黄
            >
              警告用户
            </Button>
            <Button
              type="default"
              loading={actionLoading}
              onClick={handleUnwarn}
            >
              解除警告
            </Button>
          </Space>

          <Button
            onClick={handleCancel}
            style={{ marginTop: 12, width: "100%" }}
          >
            关闭
          </Button>
        </Space>
      </Modal>
    </div>
  );
}

export default UserAdmin;
